﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sealight.Core.DataAdapter;
using Sealight.API.Framework;
using log4net;
using Sealight.API.Framework.Mail;

namespace Sealight.UI.WebUI.Areas.Admin.Controllers.Configuration
{
    [Sealight.UI.WebUI.UIHelpers.SessionExpireFilter]
    [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public class ConfigurationController : Controller
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ConfigurationController));
        public ActionResult Settings()
        {
            settings data = Services.SettingServices.GetSettings();
            return View(data);
        }

        public ActionResult _SaveSettingsData(settings data)
        {
            AjaxOperationResponse response = new AjaxOperationResponse();
            try
            {
                if (data != null)
                {
                    Services.SettingServices.AddOrUpdate(data);
                }
                return Json(bool.TrueString.ToLower());
            }
            catch (Exception ex)
            {
                log.Error("Error while _SaveSettingsData.", ex);
                response.OperationComplete = false;
                response.ErrorCode = "4001";
                response.ErrorFriendlyMessage = string.Format("{0}", UIHelpers.Message.Error);

                return Json(response);
            }
        }

        public ActionResult _TestSendMail(settings data)
        {            
            try
            {
                if (data != null)
                {
                    //Send email
                    IEmailMessage emailMessage = new EmailMessage();
                    emailMessage.From = data.Email;
                    emailMessage.To = data.Email;
                    emailMessage.Subject = "test";
                    emailMessage.Body = "test";

                    ISmtpSender smtp = new SmtpSender(data.UseAuthentication, data.EnableSsl, data.SmtpServerPort, data.SmtpServer,
                        data.SmtpUserName, data.SmtpPassword);                   
                    smtp.Send(emailMessage);
                }               

            }
            catch
            {
                return Json(bool.FalseString.ToLower());               
            }
            return Json(bool.TrueString.ToLower());
        }

    }
}
